<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 15-4-21
 * Time: 下午10:41
 */

class goods extends adminBase{
    function __construct() {
        parent::__construct();
        $this->cms->setPageTitle("商品管理");
//        $this->cms->setActionTitle("添加商品");
        $this->cms->setControlFile("admin/tpl/goods/goodscontrol.json");
        $admin_info=$this->user->getLoginInfo();
        $user=UserMode::init();
        $levels=$user->getLevels($admin_info['id']);
        if(!$user->checkLevels(6,$levels)){
            $r['message']="您不具有此权限！";
            View::displayAsHtml($r,"plugin/state/tips.php");
            exit();
        }

    }
    function indexTask($company,$goodsLabel,$goodsCat,$goodsName,$orderBy,$asc,$page=1){
        $goods=GoodsMode::init();
        $cats=MenuModule::init();
        $shop=ShopMode::init();
        $asc = $asc==1?true:false;
        if(!empty($orderBy)){
            $r[$orderBy]=$asc;
        }
        if(!empty($company)){
            $shop_name=$shop->getShopIdByCompany($company);
            $r['shopId']=isset($shop_name)?$shop_name:null;
        }else{
            $r['shopId']=null;
        }
        $r['goodsCat']=$goodsCat;
        $r['goodsLabel']=$goodsLabel;
        $r['goodsName']=isset($goodsName)? trim($goodsName):null;
        $r['paramRemain']=array('shopId'=>$r['shopId']);
        if($goodsCat!=0){
            $pos=$cats->getPosterity($goodsCat);
            $pos_ids=is_array($pos)?implode(',',$pos):$pos;
        }else{
            $pos_ids=null;
        }
        $r['goods_all_cat'] = $cats->getAll();
        $r['goods_exist_cat'] = (int)$goodsCat;
        if(!$pos_ids){
            $r['goods_cat']=$cats->getAll();
        }else{
            $r['goods_cat']=$cats->getAll($goodsCat);
        }
        usort($r['goods_cat'],function($a,$b){
            return ord(substr(iconv('utf-8', 'gbk', $a['name']), 0, 1))-
            ord(substr(iconv('utf-8', 'gbk', $b['name']), 0, 1));
        });
        $label=LabelModule::init();
        list($r['label'],$label_total)=$label->getList(30,0);
        usort($r['label'],function($a,$b){
            return ord(substr(iconv('utf-8', 'gbk', $a['name']), 0, 1))-
            ord(substr(iconv('utf-8', 'gbk', $b['name']), 0, 1));
        });
        $url=WebRouter::init()->getQuestion("company={$company}&goodsLabel={$goodsLabel}&goodsCat={$goodsCat}&goodsName={$goodsName}&orderBy={$orderBy}&asc={$asc}&page=");
        $page=$page>=1? $page: 1;
        $countOfPage=15;
        $offset=($page-1)*$countOfPage;
        list($goodsIds,$goods_total)=$goods->getList($r['shopId'],$goodsLabel,$pos_ids,$goodsName,$orderBy,$asc,$countOfPage,$offset);
        if($goods_total!=0 && !empty($goodsIds)){
            $r['goods_info']=$goods->getDetailInfo($goodsIds);
            $goods->sortGoods($r['goods_info'], "create_time", $asc);
            if(isset($asc)){
                $goods->sortGoods($r['goods_info'], $orderBy, $asc);
            }
        }else{
            $r['goods_info']=array();
        }
        $r['pages']=new Page($page,$goods_total,$countOfPage);
        $r['pages']->setPageCallback(function($page)use($url){
            return $url.$page;
        });
        $r['goods_type']=array( 'normal'=>"普通商品",'commodity'=>"大宗商品",'service'=>"服务商品",'non_sale'=>"广告商品");
        $this->cms->tableScene($r,"admin/tpl/goods/goods.php");
    }

    function modifyTask($id){
        $this->cms->setActionTitle("商品修改");
        $goods=GoodsMode::init();
        $gopen_id=$goods->getGopenId($id);
        $r=$goods->getSimpleInfo($gopen_id);
        $r['goods_type']=array( 'normal'=>"普通商品",'commodity'=>"大宗商品",'service'=>"服务商品",'non_sale'=>"广告商品");
        if(empty($r)) return new Intent(404,'商品未找到');
        $r['prices']=$goods->getPrice($r['price_id']);
        $tip=ArticleModule::init('tip');
        list($r['tip'],$tip_total)=$tip->getList(null,30,0);
        $menu=MenuModule::init();
        $catTree=$menu->getAll();
        $r['goods_cat']=$this->fetchTree($catTree);
        $label=LabelModule::init();
        list($r['label'],$label_total)=$label->getList();
        $this->cms->normalScene($r,"admin/tpl/goods/goodsModify.php",
            CmsView::TYPE_FORM| CmsView::TYPE_JQUERY| CmsView::TYPE_EDITOR);
    }

    function modifySubmitTask($goods_id,$gopen_id,$goodsName,$goods_cat_id,$unit,$detail,$tip_id,
                              $price_id,$bonus,$commission,$service_fee,$platform_fee,$label=array(),$qq,$note,$supplier,
                              $original_price,$base_price,$low,$medium,$medium_price,$high_price){
        $goods=GoodsMode::init();

        $original_price=isset($original_price)?trim($original_price):null;
        $base_price=isset($base_price)?trim($base_price):null;
        $low=isset($low)?trim($low):null;
        $medium=isset($medium)?trim($medium):null;
        $medium_price=isset($medium_price)?trim($medium_price):null;
        $high_price=isset($high_price)?trim($high_price):null;
        $price_result=$goods->modifyPrice($price_id,$gopen_id,$original_price,$base_price,$low,
            $medium,$medium_price,$high_price);
        if($price_result>0){
            $price_id=$price_result;
        }
        $goods_info=$goods->getDetailInfo($gopen_id);
        $goods_result=$goods->modify($goods_id,$gopen_id,$goodsName,$goods_cat_id,$unit,$detail,$goods_info['stock'],$goods_info['pic_ids'],$goods_info['thumb_pic'], $tip_id,
            $price_id,$bonus,$commission,$service_fee,$platform_fee,implode(",",$label),$qq,$note,$supplier);
        if(!$goods_result||!$price_result){
            $r['url']=WebRouter::init()->getPage("goods","index");
            $r['message']="商品修改成功";
        }else{
            $r['message']="未修改或修改失败，请重试！";
        }
        View::displayAsHtml($r,"plugin/state/tips.php");
    }

    function deleteTask($id){
        $goods=GoodsMode::init();
        if($goods->delete($id)){
            $r['url']=WebRouter::init()->getPage("goods","index");
            $r['message']="商品删除成功";
        }else{
            $r['message']="商品删除失败，请重试！";
        }
        View::displayAsHtml($r,"plugin/state/tips.php");
    }

    function fetchTree($array){
        $temp=array();
        foreach($array as $v){
            if(!empty($v['children'])) $temp=array_merge($temp, $this->fetchTree($v['children']));
            unset($v['children']);
            $temp[]=$v;
        }
        return $temp;
    }

    function addTask(){
        $this->cms->setActionTitle("添加商品");
        $shop=ShopMode::init();
        list($r['shop_info'],$shop_total)=$shop->getList(2,100,0);
        $label=LabelModule::init();
        list($r['label'],$label_total)=$label->getList(30,0);
        $tip=ArticleModule::init('tip');
        list($r['tip'],$tip_total)=$tip->getList(null,30,0);
        $menu=MenuModule::init();
        $catTree=$menu->getAll();
        $r['goods_cat']=$this->fetchTree($catTree);
        $this->cms->normalScene($r,"admin/tpl/goods/goodsAdd.php",
            CmsView::TYPE_FORM| CmsView::TYPE_JQUERY| CmsView::TYPE_EDITOR);
    }

    function addSubmitTask($shopId,$name,$goodsCat,$unit,$detail,$pic_ids,$thumb_pic,$tip_id,$bonus,$commission,$service_fee,$type,$label=array(),
                           $goods_attr,$original_price,$base_price,$low,$medium_price,$medium,$high_price,$qq,$note,$supplier){
        $goods=GoodsMode::init();
        $stock=0;
        if($goods_attr){
            foreach($goods_attr as $v){
                $stock+=$v['stock'];
            }
        }
        $price_id=$goods->addPrice(0,$original_price,$base_price,$low,$medium_price,$medium,$high_price);
        $gopen_id=$goods->add($shopId,$name,$goodsCat,$unit,$detail,$stock,$pic_ids,$thumb_pic,$tip_id,$price_id,
            $bonus,$commission,$service_fee,$type,implode(",",$label),$qq,$note,$supplier);
        $g1=$goods->modifyPrice($price_id,$gopen_id,$original_price,$base_price);
        $g2=$goods->addAttr($gopen_id,$goods_attr);
        if(!$g1||$g2){
            $r['url']=WebRouter::init()->getPage("goods","index");
            $r['message']="商品添加成功";
        }else{
            $r['message']="商品添加失败，请重试";
        }
        View::displayAsHtml($r,"plugin/state/tips.php");
    }

    // 添加图片
    function picTask($gopen_id){
        $this->cms->setActionTitle("图片管理");
        $goods=GoodsMode::init();
        $r=$goods->getDetailInfo($gopen_id);
        $this->cms->tableScene($r,"admin/tpl/goods/pic.php");
    }
    function picAddTask($gopen_id){
        $this->cms->setActionTitle("添加图片");
        $r['gopen_id']=$gopen_id;
        $this->cms->formScene($r,"admin/tpl/goods/picAdd.php");
    }
    function picAddSubmitTask($gopen_id, $thumb=false){
        $up=Uploader::init();
        $pic=PictureModule::init("picture");
        $goods=GoodsMode::init();
        $picArray=array( array('set'=>"goods","width"=>800,'height'=>600) );
        if($thumb) $picArray[]=array('set'=>"thumb","width"=>200,'height'=>200);
        list($stateInfo,$picDataArray)=$up->upImage('file',null,$picArray);
        if(strtolower($stateInfo)=='success'){
            foreach($picDataArray as &$picData){
                $picData['photoId']=$pic->add($picData['url'],$picData['savePath'],$picData['filename']);
            }
            // 更新商品信息
            $goodsData=$goods->getDetailWithoutJoin($gopen_id);
            $picIdsArray=explode(",",$goodsData['pic_ids']);
            $picIdsArray[]=$picDataArray['goods']['photoId'];
            $thumbId=$thumb? $picDataArray['thumb']['photoId']: null;
            $goods->modify($goodsData['id'],$goodsData['gopen_id'],null,null,null,null,null,join(',',$picIdsArray),$thumbId,null,null);
            $r['url']=WebRouter::init()->getAction("pic",'gopen_id='.$gopen_id);
            $r['message']="图片添加成功";
        }else{
            $r['message']="图片添加失败";
        }
        $r['gopen_id']=$gopen_id;
        View::displayAsHtml($r,"plugin/state/tips.php");
    }
    function picDeleteTask($gopen_id, $id){
        $goods=GoodsMode::init();
        $goodsData=$goods->getDetailInfo($gopen_id);
        $picIdsArray=explode(",",$goodsData['pic_ids']);
        $picIdsArray=array_filter($picIdsArray,function($v)use($id){
            return $v!=$id;
        });
        if(!empty($picIdsArray)){
            $goods->modify($goodsData['id'],$goodsData['gopen_id'],null,null,null,null,null,join(',',$picIdsArray),null,null,null);
            $r['message']="图片删除成功";
        }else{
            $r['message']="最后一张图片请不要删除";
        }
        $r['url']=WebRouter::init()->getAction("pic",'gopen_id='.$gopen_id);
        View::displayAsHtml($r,"plugin/state/tips.php");
    }

    function natureTask($id){
        $this->cms->setActionTitle("查看属性");
        $goods=GoodsMode::init();
        $gopen_id=$goods->getGopenId($id);
        $r=$goods->getDetailInfo($gopen_id);
        $this->cms->tableScene($r,"admin/tpl/goods/nature.php");
    }

    function addNatureTask($id){
        $this->cms->setActionTitle("添加属性");
        $r['gopen_id']=$id;
        $this->cms->formScene($r,"admin/tpl/goods/addNature.php");
    }

    function addNatureSubmitTask($gopen_id,$name,$stock){
        $goods=GoodsMode::init();
        $attr=array(array("name"=>$name,"stock"=>$stock));
        $goods->addAttr($gopen_id,$attr);
        $goods_info=$goods->getDetailInfo($gopen_id);
        $stock=(isset($goods_info['stock'])?$stock+$goods_info['stock']:$stock);
        $g=$goods->modify($goods_info['id'],$gopen_id,$goods_info['name'],$goods_info['goods_cat_id'],$goods_info['unit'],$goods_info['detail'],$stock,$goods_info['pic_ids'],$goods_info['thumb_pic'], $goods_info['tip_id'],
            $goods_info['price_id'],$goods_info['bonus'],$goods_info['commission'],$goods_info['service_fee'],$goods_info['platform_fee'],$goods_info['label_ids'],$goods_info['qq'],$goods_info['note'],$goods_info['supplier']);
        if(!$g){
            $r['url']=WebRouter::init()->getAction("nature",'id='.$goods_info['id']);
            $r['message']="属性添加成功";
        }else{
            $r['message']="属性添加失败，请重试！";
        }
        View::displayAsHtml($r,"plugin/state/tips.php");
    }

    function natureModifyTask($id){
        $this->cms->setActionTitle("修改属性");
        $goods=GoodsMode::init();
        $r=$goods->getAttrDetail($id);
        $this->cms->formScene($r,"admin/tpl/goods/natureModify.php");
    }

    function natureModifySubmitTask($id,$name,$stock){
        $goods=GoodsMode::init();
        $old_attr=$goods->getAttrDetail($id);
        $goods_info=$goods->getDetailInfo($old_attr['gopen_id']);
        $goods->modifyAttr($id,$name,$stock);
        $stock=(isset($goods_info['stock'])?$goods_info['stock']-$old_attr['stock']+$stock:$stock);
        $g=$goods->modify($goods_info['id'],$goods_info['gopen_id'],$goods_info['name'],$goods_info['goods_cat_id'],$goods_info['unit'],$goods_info['detail'],$stock,$goods_info['pic_ids'],$goods_info['thumb_pic'], $goods_info['tip_id'],
            $goods_info['price_id'],$goods_info['bonus'],$goods_info['commission'],$goods_info['service_fee'],$goods_info['platform_fee'],$goods_info['label_ids'],$goods_info['qq'],$goods_info['note'],$goods_info['supplier']);
        if(!$g){
            $r['url']=WebRouter::init()->getAction("nature",'id='.$goods_info['id']);
            $r['message']="属性修改成功";
        }else{
            $r['message']="未被修改或修改失败，请重试！";
        }
        View::displayAsHtml($r,"plugin/state/tips.php");
    }

    function natureDeleteTask($id){
        $goods=GoodsMode::init();
        $attr=$goods->getAttrDetail($id);
        $goods_info=$goods->getDetailInfo($attr['gopen_id']);
        if($goods->deleteAttr($id)){
            $stock=(isset($goods_info['stock'])?$goods_info['stock']-$attr['stock']:0);
            $g=$goods->modify($goods_info['id'],$goods_info['gopen_id'],$goods_info['name'],$goods_info['goods_cat_id'],$goods_info['unit'],$goods_info['detail'],$stock,$goods_info['pic_ids'],$goods_info['thumb_pic'], $goods_info['tip_id'],
                $goods_info['price_id'],$goods_info['bonus'],$goods_info['commission'],$goods_info['service_fee'],$goods_info['platform_fee'],$goods_info['label_ids'],$goods_info['qq'],$goods_info['note'],$goods_info['supplier']);
            if(!$g){
                $r['url']=WebRouter::init()->getAction("nature",'id='.$goods_info['id']);
                $r['message']="属性删除成功";
            }else{
                $r['message']="属性删除失败，请重试！";
            }
            View::displayAsHtml($r,"plugin/state/tips.php");
        }
    }

    function categoryTask($id=0){
        $this->cms->setActionTitle("商品类别管理");
        $cats=MenuModule::init();
        $r['catTree']=$cats->getAll($id);
        $r['pid']=$id;
        $this->cms->tableScene($r,"admin/tpl/goods/category.php");
    }

    function categoryAddTask($pid){
        $r['pid']=$pid;
        $this->cms->formScene($r,"admin/tpl/goods/categoryAdd.php");
    }

    function categoryAddSubmitTask($name,$pid=0,$point=0){
        $cats=MenuModule::init();
        if($cats->add($name,$pid,$point)){
            if(!$pid){
                $r['url']=WebRouter::init()->getAction("category",'id='.$pid);
                $r['message']="主类添加成功";
            }else{
                $r['url']=WebRouter::init()->getAction("category",'id='.$pid);
                $r['message']="子类添加成功";
            }
            View::displayAsHtml($r,"plugin/state/tips.php");
        }
    }

    function categoryModifyTask($id){
        $cats=MenuModule::init();
        $r=$cats->getDetail($id);
        $this->cms->formScene($r,"admin/tpl/goods/categoryModify.php");
    }

    function categoryModifySubmitTask($id,$pid,$name,$point=0){
        $cats=MenuModule::init();
        if($cats->modify($id,$name,$pid,$point)){
            $r['message']="类别修改成功";
            $r['url']=WebRouter::init()->getAction("category",'id='.$pid);
        }else{
            $r['message']="修改失败，请重试";
        }
        View::displayAsHtml($r,"plugin/state/tips.php");
    }

    function categoryDeleteTask($id){
        $goods=GoodsMode::init();
        $cats=MenuModule::init();
        $cats_detial=$cats->getDetail($id);
        $cats_info=$cats->getSon($id);
        $goods_total=$goods->getTotalByCatId($cats_detial['id']);
        if($goods_total!=0||(!empty($cats_info))){
            $r['url']=WebRouter::init()->getAction("category",'id='.$cats_detial['pid']);
            $r['message']="该类别不能被删除";
        }else{
            if($cats->deleteRelated($id)){
                $r['url']=WebRouter::init()->getAction("category",'id='.$cats_detial['pid']);
                $r['message']="类别删除成功";
            }else{
                $r['message']="删除失败，请重试！";
            }
        }
        View::displayAsHtml($r,"plugin/state/tips.php");
    }


    // 买家须知查看修改
    function tipTask($page){
        $article=ArticleModule::init('tip');
        $page=$page>=1? $page: 1;
        $countOfPage=20;
        $offset=($page-1)*$countOfPage;
        list($r['list'],$total)=$article->getList(null,$countOfPage,$offset);
        $r['page']=new Page($page,$total);
        $url=WebRouter::init()->getQuestion("page=");
        $r['page']->setPageCallback(function($page)use($url){
            return $url.$page;
        });
        $this->cms->tableScene($r,"admin/tpl/goods/tipList.php");
    }

    function tipAddTask(){
        $r=array();
        $this->cms->normalScene($r,"admin/tpl/goods/tipAdd.php",
            CmsView::TYPE_FORM| CmsView::TYPE_JQUERY| CmsView::TYPE_EDITOR);
    }
    function tipModifyTask($id){
        $article=ArticleModule::init('tip');
        $r=$article->getDetail($id);
        if(empty($r)) return new Intent(404,"买家须知未找到");
        $this->cms->normalScene($r,"admin/tpl/goods/tipModify.php",
            CmsView::TYPE_FORM| CmsView::TYPE_JQUERY| CmsView::TYPE_EDITOR);
    }
    function tipSubmitTask($id,$title,$content){
        $article=ArticleModule::init('tip');
        $articleData=$article->getDetail($id);
        if(!empty($articleData)){
            $article->modify($id, $title, $content);
            $r['message']="修改成功";
        }else{
            $article->add($title,$content);
            $r['message']="添加成功";
        }
        $r['url']=WebRouter::init()->getAction('tip');
        View::displayAsHtml($r,"plugin/state/tips.php");
    }

    function tipDeleteTask($id){
        $article=ArticleModule::init('tip');
        $re=$article->delete($id);
        if($re){
            $r['message']="删除成功";
        }else{
            $r['message']="删除失败，请重试";
        }
        View::displayAsHtml($r,"plugin/state/tips.php");
    }
} 